import {
  Injectable,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { UpdateUserDto, UserProfileResponseDto } from './dto/user.dto';
import * as bcrypt from 'bcrypt';

@Injectable()
export class UserService {
  constructor(private readonly prisma: PrismaService) {}

  /**
   * 获取用户详情
   */
  async getUserProfile(userId: number): Promise<UserProfileResponseDto> {
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
      select: {
        id: true,
        nickname: true,
        avatar: true,
        email: true,
        phone: true,
        bio: true,
        wechat: true,
        qq: true,
        points: true,
        studyTime: true,
        shortsCount: true,
        createdAt: true,
        updatedAt: true,
      },
    });

    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    return {
      ...user,
      avatar: user.avatar || undefined, // 处理null值
      email: user.email || undefined,
      phone: user.phone || undefined,
      bio: user.bio || undefined,
      wechat: user.wechat || undefined,
      qq: user.qq || undefined,
      createdAt: user.createdAt.toISOString(),
      updatedAt: user.updatedAt.toISOString(),
    };
  }

  /**
   * 更新用户信息
   */
  async updateUser(
    userId: number,
    updateDto: UpdateUserDto,
  ): Promise<UserProfileResponseDto> {
    // 检查用户是否存在
    const existingUser = await this.prisma.user.findUnique({
      where: { id: userId },
    });

    if (!existingUser) {
      throw new NotFoundException('用户不存在');
    }

    // 如果更新昵称，检查昵称是否已被其他用户使用
    if (updateDto.nickname && updateDto.nickname !== existingUser.nickname) {
      const nicknameExists = await this.prisma.user.findFirst({
        where: {
          nickname: updateDto.nickname,
          id: { not: userId },
        },
      });

      if (nicknameExists) {
        throw new BadRequestException('昵称已被其他用户使用');
      }
    }

    // 更新用户信息
    const updatedUser = await this.prisma.user.update({
      where: { id: userId },
      data: {
        ...updateDto,
        updatedAt: new Date(),
      },
      select: {
        id: true,
        nickname: true,
        avatar: true,
        email: true,
        phone: true,
        bio: true,
        wechat: true,
        qq: true,
        points: true,
        studyTime: true,
        shortsCount: true,
        createdAt: true,
        updatedAt: true,
      },
    });

    return {
      ...updatedUser,
      avatar: updatedUser.avatar || undefined,
      email: updatedUser.email || undefined,
      phone: updatedUser.phone || undefined,
      bio: updatedUser.bio || undefined,
      wechat: updatedUser.wechat || undefined,
      qq: updatedUser.qq || undefined,
      createdAt: updatedUser.createdAt.toISOString(),
      updatedAt: updatedUser.updatedAt.toISOString(),
    };
  }

  /**
   * 更新用户密码
   */
  async updatePassword(
    userId: number,
    currentPassword: string,
    newPassword: string,
  ): Promise<void> {
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
      select: { id: true, password: true },
    });

    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    // 验证当前密码
    const isCurrentPasswordValid = await bcrypt.compare(
      currentPassword,
      user.password,
    );
    if (!isCurrentPasswordValid) {
      throw new BadRequestException('当前密码不正确');
    }

    // 加密新密码
    const hashedNewPassword = await bcrypt.hash(newPassword, 10);

    // 更新密码
    await this.prisma.user.update({
      where: { id: userId },
      data: {
        password: hashedNewPassword,
        updatedAt: new Date(),
      },
    });
  }

  /**
   * 删除用户账户
   */
  async deleteAccount(userId: number): Promise<void> {
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
    });

    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    // 删除用户相关数据（级联删除）
    await this.prisma.user.delete({
      where: { id: userId },
    });
  }

  /**
   * 增加用户积分
   */
  async addPoints(
    userId: number,
    points: number,
    reason?: string,
  ): Promise<void> {
    await this.prisma.user.update({
      where: { id: userId },
      data: {
        points: { increment: points },
        updatedAt: new Date(),
      },
    });

    // 可以在这里添加积分记录日志
    // await this.prisma.pointsLog.create({...})
  }

  /**
   * 扣除用户积分
   */
  async deductPoints(
    userId: number,
    points: number,
    reason?: string,
  ): Promise<void> {
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
      select: { points: true },
    });

    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    if (user.points < points) {
      throw new BadRequestException('积分不足');
    }

    await this.prisma.user.update({
      where: { id: userId },
      data: {
        points: { decrement: points },
        updatedAt: new Date(),
      },
    });

    // 可以在这里添加积分记录日志
    // await this.prisma.pointsLog.create({...})
  }
}
